using System.Collections.Generic;
using Kopernikus.Collections.Generic;
using Kopernikus.Parsing.Utility;

namespace Kopernikus.Parsing.GrammarSets
{
    public class ProductionsByLHS
    {
        private readonly IGrammar m_grammar;
        private SetMap<Symbol, Production> m_lhs;
        private Dictionary<Symbol, Production> m_nullableProductionsByLHS;

        public ProductionsByLHS(IGrammar grammar)
        {
            m_grammar = grammar;
        }

        public IGrammar Grammar
        {
            get { return m_grammar; }
        }

        public Set<Production> GetProductionsByLHS(Symbol s)
        {
            if (m_lhs == null)
            {
                m_lhs = new SetMap<Symbol, Production>();
                foreach (Production p in Grammar.Productions)
                {
                    m_lhs.MakeSet(p.LHS).Add(p);
                }
            }
            return m_lhs.GetSet(s);
        }

        public Production GetNullableProductionByLHS(Symbol s)
        {
            if (m_nullableProductionsByLHS == null)
            {
                m_nullableProductionsByLHS = new Dictionary<Symbol, Production>();
                foreach (Production p in m_grammar.ProductionSets.NullableProductions)
                {
                    bool add = true;
                    Production existingNullable;
                    if (m_nullableProductionsByLHS.TryGetValue(p.LHS, out existingNullable))
                    {
                        add = existingNullable.RHS.Length > p.RHS.Length;
                    }
                    if (add)
                    {
                        m_nullableProductionsByLHS[p.LHS] = p;
                    }
                }
            }
            return m_nullableProductionsByLHS[s];
        }
    }
}